package com.shopmall.manager.service.impl;

import com.alibaba.excel.EasyExcel;
import com.shopmall.common.exception.CustomException;
import com.shopmall.manager.listener.ExcelListener;
import com.shopmall.manager.mapper.CategoryMapper;
import com.shopmall.manager.service.CategoryService;
import com.shopmall.model.entity.product.Category;
import com.shopmall.model.vo.common.ResultCodeEnum;
import com.shopmall.model.vo.product.CategoryExcelVo;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> findCategoryList(Long id) {
        // 分类列表，每次查询一层数据
        List<Category> categoryList = categoryMapper.selectCategoryByParentId(id);
        // 判断每个分类是否有下一层，有则设置hasChildren = true
        if (!CollectionUtils.isEmpty(categoryList)) {
            categoryList.forEach(category -> {
                // 判断每一分类是否有下一层分类
                String count = categoryMapper.selectCountByParentId(category.getId());
                category.setHasChildren(count != null); // 返回值 count != null true或者false
            });
        }
        return categoryList;
    }

    // 导出
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            // 设置响应头信息和其他信息
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 设置编码格式
            String fileName = URLEncoder.encode("分类数据", StandardCharsets.UTF_8);
            // 设置响应头信息
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            // 调用mapper方法查询所有分类，返回list集合
            List<Category> categoryList = categoryMapper.findAll();
            // 实体类型转换
            List<CategoryExcelVo> categoryExcelVoList = new ArrayList<>();
            for (Category category : categoryList) {
                CategoryExcelVo categoryExcelVo = new CategoryExcelVo();
                // 把category值获取出来，设置到categoryExcelVo里面
                BeanUtils.copyProperties(category, categoryExcelVo);
                categoryExcelVoList.add(categoryExcelVo);
            }
            // 调用EasyExcel的write方法完成写操作
            EasyExcel.write(response.getOutputStream(), CategoryExcelVo.class)
                    .sheet("分类数据").doWrite(categoryExcelVoList);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException(ResultCodeEnum.DATA_ERROR);
        }
    }

    // 导入
    @Override
    public String importData(MultipartFile file) {
        // 监听器
        ExcelListener<CategoryExcelVo> excelListener = new ExcelListener<>(categoryMapper);
        try {
            EasyExcel.read(file.getInputStream(), CategoryExcelVo.class, excelListener)
                    .sheet().doRead();
            return "ok";
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException(ResultCodeEnum.DATA_ERROR);
        }

    }
}
